package cn.fl.sue.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.comm.facade.upload.condition.SysUlDatCfgQueryCondition;
import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.comm.facade.upload.dto.SysUlDatCfgDTO;
import cmm.comm.facade.upload.dto.SysUlDatCfgDtlDTO;
import cmm.comm.facade.upload.dto.SysUlFilesRecDTO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.project.condition.PrjFileInfoQueryCondition;
import cn.fl.project.vo.PrjFileInfoVO;
import cn.fl.sue.api.ISueApplyViewApiService;
import cn.fl.sue.api.ISueBscInfoApiService;
import cn.fl.sue.condition.SueBscInfoQC;
import cn.fl.sue.condition.SueFileInfoQC;
import cn.fl.sue.constant.SueConstant;
import cn.fl.sue.dto.SueBscInfoDTO;
import cn.fl.sue.service.ISueApplyViewService;
import cn.fl.sue.service.ISueBscInfoService;
import cn.fl.sue.vo.SueApplyViewDtlVO;
import cn.fl.sue.vo.SueBscInfoVO;
import cn.fl.sue.vo.SueFileVO;
import cn.fl.sue.voTransform.SueApplyViewDtlVOTransform;
import cn.fl.sue.voTransform.SueBscInfoVOTransform;
import cn.fl.system.api.ISysSequenceApiService;
import cn.fl.system.transform.SysUlDatCfgDtlVOTransform;
import cn.fl.system.vo.SysUlDatCfgDtlVO;
import cn.fl.upload.constant.UploadConstant;
import fl.flow.facade.flow.api.IFlowApiService;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.fl.framework.base.context.CurrentThreadContext;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;

/**
 * @Author: huangkailun
 * @Description: 诉讼信息表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class SueBscInfoServiceImpl implements ISueBscInfoService {

    /**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(ISueBscInfoService.class);
    /**
     * 数据字典服务
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    /**
     * 诉讼记录信息表服务
     */
    @Autowired
    private ISueBscInfoApiService sueBscInfoApiService;

    /**
     * 上传文件的api接口服务
     */
    @Autowired
    private IUploadApiService uploadApiService;

    /**
     * 序列的接口api
     */
    @Autowired
    private ISysSequenceApiService sysSequenceApiService;

    /**
     * 诉讼申请的显示接口api
     */
    @Autowired
    private ISueApplyViewApiService sueApplyViewApiService;

    /**
     * 发起流程的接口api
     */
    @Autowired
    private IFlowApiService flowApiService;

    @Override
    public SueBscInfoVO selectById(Long id) throws BaseException {
        if (StringUtils.isEmpty(id)) {
            BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
            return null;
        }
        SueBscInfoDTO dto = sueBscInfoApiService.selectSueBscInfoById(id);//this.自定义ApiService.selectById(id);
        return SueBscInfoVOTransform.toVO(dto);
    }

    @Override
    public Long add(SueBscInfoVO entity) throws BaseException {
        if (null == entity) {
            BaseLogUtils.info(logger, "add", "新增对象不能为空!", CurrentThreadContext.getCurrentUserName());
            return null;
        }
        return this.sueBscInfoApiService.addSueBscInfo(SueBscInfoVOTransform.toDTO(entity));
    }

    @Override
    public boolean removeById(Long id) throws BaseException {
        if (StringUtils.isEmpty(id)) {
            BaseLogUtils.info(logger, "removeById", "删除主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
            return false;
        }
        //return this.sueBscInfoApiService.removeById(id);
        return false;
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    public boolean removeByIds(List<Long> ids) throws BaseException {
        if (CollectionUtils.isEmpty(ids)) {
            BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
            return false;
        }
        ;
        return false;
    }

    @Override
    public boolean modify(SueBscInfoVO entity) throws BaseException {
        if (null == entity) {
            BaseLogUtils.info(logger, "modify", "修改对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
            return false;
        }
        //return this.sueBscInfoApiService.modify(SueBscInfoVOTransform.toDTO(entity));
        return false;
    }

    @Override
    public Pager searchListPage(Pager page) throws BaseException {
        if (null == page) {
            page = new Pager();
        }
        // 诉讼进度
        List<KeyValueVO> sueProgress = this.searchCdList(DictionaryConstant.CODE_SUE_PROGRESS);
        // 判决结果
        List<KeyValueVO> sueRes = this.searchCdList(DictionaryConstant.CODE_JUDGE_RES);
        // 结案状态
        List<KeyValueVO> caseRes = this.searchCdList(DictionaryConstant.CODE_CASE_RES);

        Pager pager = this.sueBscInfoApiService.searchSueBscInfoListPage(page);
        List<SueBscInfoDTO> list = (List<SueBscInfoDTO>) pager.getResultList();
        List<SueBscInfoVO> voList = null;
        if (CollectionUtils.isNotEmpty(list)) {
            voList = SueBscInfoVOTransform.toVOList(list);
            for (SueBscInfoVO sue : voList) {
                for (KeyValueVO progress : sueProgress) {
                    if (StringUtils.isNotEmpty(sue.getProcessCd())) {
                        if (sue.getProcessCd().equals(progress.getKey())) {
                            sue.setProcessNm(progress.getValue());
                            break;
                        }
                    }
                }
                for (KeyValueVO res : sueRes) {
                    if (StringUtils.isNotEmpty(sue.getJudgeRstCd())) {
                        if (sue.getJudgeRstCd().equals(res.getKey())) {
                            sue.setJudgeRstNm(res.getValue());
                            break;
                        }
                    }
                }
                for (KeyValueVO caseR : caseRes) {
                    if (StringUtils.isNotEmpty(sue.getCaseRstCd())) {
                        if (sue.getCaseRstCd().equals(caseR.getKey())) {
                            sue.setCaseRstNm(caseR.getValue());
                            break;
                        }
                    }
                }
            }
        } else {
            voList = new ArrayList<>();
        }
        pager.setResultList(voList);
        return pager;
    }

    /**
     * 查询数据字典
     *
     * @param groupCd 组代码
     * @return List<KeyValueVO>
     */
    @Override
    public List<KeyValueVO> searchCdList(String groupCd) {
        return this.sysDictionaryApiService.getKvList(groupCd, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
    }

    /**
     * 通过配置编号查询诉讼文件的配置信息
     *
     * @param condition
     * @return
     */
    @Override
    public List<SueFileVO> searchSueFileCfgDtlAndFileCfg(SueFileInfoQC condition) {
        return this.getSueUploadFileList(condition);
    }

    /**
     * 获取诉讼记录文件的全部信息
     *
     * @param condition
     * @return
     * @throws BaseException
     */
    private List<SueFileVO> getSueUploadFileList(SueFileInfoQC condition) throws BaseException {
        // 查询资料主配置：系统代码，组织架构代码，配置编号
        SysUlDatCfgQueryCondition ulDatCfgQueryCondition = new SysUlDatCfgQueryCondition();
        ulDatCfgQueryCondition.setOrgCd(condition.getOrgCd());
        ulDatCfgQueryCondition.setSysCd(CurrentThreadContext.getCurrentSysCd());//系统代码
        ulDatCfgQueryCondition.setCfgCdList(condition.getCfgCdList());//配置编号集合
        // 数据主键ID
        ulDatCfgQueryCondition.setDataId(String.valueOf(condition.getSueId()));
        List<SysUlDatCfgDTO> list = uploadApiService.searchSysUlDatCfgListByDataId(ulDatCfgQueryCondition);
        // 查询文件上传记录：数据主键
        SysUlFilesRecQueryCondition sysUlFilesRecQueryCondition = new SysUlFilesRecQueryCondition();
        if (StringUtils.isNotEmpty(condition.getSueId())) {
            sysUlFilesRecQueryCondition.setPkId(String.valueOf(condition.getSueId()));
        }
        String crtUsrNm = null;
        SueBscInfoVO sueBscInfoVO = this.selectById(Long.valueOf(condition.getSueId()));
        if (null != sueBscInfoVO) {
            crtUsrNm = sueBscInfoVO.getCrtUsrNm();
        }
        // 整合配置和文件上传记录到诉讼记录文件的VO
        List<SueFileVO> voList = null;
        if (CollectionUtils.isNotEmpty(list)) {
            voList = new ArrayList<>();
            SueFileVO vo;
            //设置路径
            String picServicePath = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_SERVER_PATH);
            for (SysUlDatCfgDTO dto : list) {
                for (SysUlDatCfgDtlDTO dtlDTO : dto.getSysUlDatCfgDtlDTOList()) {
                    vo = new SueFileVO();
                    vo.setId(condition.getDataId());//业务主键
                    vo.setCfgDtlCd(dtlDTO.getCfgDtlCd());//配置子编号
                    vo.setDatNm(dtlDTO.getDatNm());//配置名称
                    vo.setCfgCd(dtlDTO.getCfgCd());//配置编号
                    vo.setOrgCd(dtlDTO.getOrgCd());//配置组织架构代码
                    vo.setCfgNm(dto.getCfgNm());//配置子名称
                    vo.setFileId(dtlDTO.getRecId());//附件ID
                    //如果有HTTP开头说明是可以访问路径,无需干涉
                    if (StringUtils.isNotBlank(dtlDTO.getFilePath()) && !dtlDTO.getFilePath().startsWith("http") && StringUtils.isNotBlank(picServicePath)) {
                        vo.setFilePath(picServicePath + dtlDTO.getFilePath());
                    } else {
                        vo.setFilePath(dtlDTO.getFilePath());
                    }
                    vo.setFileNm(dtlDTO.getRecFileNm());//上传名称
                    vo.setCrtTm(dtlDTO.getRecCrtTm());//上传时间
                    vo.setIsMust(dtlDTO.getIsMust());//是否必传
                    if (StringUtils.isNotEmpty(dtlDTO.getRecFileNm())) {
                        vo.setUpUsrNm(CurrentThreadContext.getCurrentUserName());
                    }
                    if (StringUtils.isNotEmpty(crtUsrNm)) {
                        vo.setUpUsrNm(crtUsrNm);
                    }
                    voList.add(vo);
                }
            }
        }
        return voList;
    }

    /**
     * 根据序列名称获取诉讼信息序列
     *
     * @return
     */
    @Override
    public Long getSueBscInfoSeq() {
        return sysSequenceApiService.getFun(SueConstant.SUE_BSC_INFO_REQ_FUN);
    }

    /**
     * 查询全部的诉讼记录
     *
     * @param condition
     * @return
     */
    @Override
    public List<SueBscInfoVO> searchList(SueBscInfoQC condition) {
        return SueBscInfoVOTransform.toVOList(sueBscInfoApiService.searchSueBscInfoList(condition));
    }

    /**
     * 根据业务主键id和表名查询支付表明细信息
     *
     * @param dataId
     * @param tableNm
     * @return
     * @throws BaseException
     */
    @Override
    public List<SueApplyViewDtlVO> selectPaySchList(Long dataId, String tableNm) throws BaseException {
        return SueApplyViewDtlVOTransform.toVOList(sueApplyViewApiService.selectDtlList(dataId, tableNm));
    }

    /**
     * 发起结案审批流程
     * @param flowStartParamsDTO
     * @throws BaseException
     */
    @Override
    public void startCaseFinishedFlow(FlowStartParamsDTO flowStartParamsDTO) throws BaseException {
        flowApiService.noTransFlowStart(flowStartParamsDTO);
    }
}
